package com.genius.dingding.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiSnsGetuserinfoBycodeRequest;
import com.dingtalk.api.request.OapiUserGetRequest;
import com.dingtalk.api.request.OapiUserGetUseridByUnionidRequest;
import com.dingtalk.api.request.OapiUserGetuserinfoRequest;
import com.dingtalk.api.request.OapiUserSimplelistRequest;
import com.dingtalk.api.response.OapiSnsGetuserinfoBycodeResponse;
import com.dingtalk.api.response.OapiUserGetResponse;
import com.dingtalk.api.response.OapiUserGetUseridByUnionidResponse;
import com.dingtalk.api.response.OapiUserGetuserinfoResponse;
import com.dingtalk.api.response.OapiUserSimplelistResponse;
import com.dingtalk.api.response.OapiUserSimplelistResponse.Userlist;
import com.taobao.api.ApiException;


/**
 * 通讯录成员相关的接口调用
 */
public class UserHelper {


    /**
     * 根据免登授权码查询免登用户userId
     *
     * @param accessToken
     * @param code
     * @return
     * @throws Exception
     */
    public static String getUserId(String accessToken, String code){
    	DingTalkClient client = new DefaultDingTalkClient(GeniusConfig.OAPI_HOST+"/user/getuserinfo");
    	OapiUserGetuserinfoRequest request = new OapiUserGetuserinfoRequest();
    	request.setCode(code);
    	request.setHttpMethod("GET");
    	OapiUserGetuserinfoResponse response = null;
		try {
			response = client.execute(request, accessToken);
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return response.getUserid();
    }
/**
 * 第三方网站免登获取人员
 * @param accessToken
 * @param userid
 * @return
 */
    public static String getUserIdBycode(String tmp_auth_code){
    	String userId = "";
    	DefaultDingTalkClient  client = new DefaultDingTalkClient(GeniusConfig.OAPI_HOST+"/sns/getuserinfo_bycode");
    	OapiSnsGetuserinfoBycodeRequest req = new OapiSnsGetuserinfoBycodeRequest();
    	req.setTmpAuthCode(tmp_auth_code);
    	OapiSnsGetuserinfoBycodeResponse response = null;
    	try {
			response = client.execute(req,GeniusConfig.APPID,GeniusConfig.APPSECRET);
			//成功获取unionid，通过unionid获取userid
			if(response.getErrcode() == 0){
				userId = getUserIdByUnionid(GetDingDing.getInstance().getToken(), response.getUserInfo().getUnionid());
			}
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return userId;
    }
    /**
     * 第三方网站免登获取人员
     * @param accessToken
     * @param userid
     * @return
     */
        public static String getUserIdBycode(String accessToken,String tmp_auth_code){
        	String userId = "";
        	DefaultDingTalkClient  client = new DefaultDingTalkClient(GeniusConfig.OAPI_HOST+"/sns/getuserinfo_bycode");
        	OapiSnsGetuserinfoBycodeRequest req = new OapiSnsGetuserinfoBycodeRequest();
        	req.setTmpAuthCode(tmp_auth_code);
        	OapiSnsGetuserinfoBycodeResponse response = null;
        	try {
    			response = client.execute(req,GeniusConfig.APPID,GeniusConfig.APPSECRET);
    			//成功获取unionid，通过unionid获取userid
    			if(response.getErrcode() == 0){
    				userId = getUserIdByUnionid(accessToken, response.getUserInfo().getUnionid());
    			}
    		} catch (ApiException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		return userId;
        }
    /**
     * 通过unionid获取用户userid
     * @param accessToken
     * @param userid
     * @return
     */
    public static String getUserIdByUnionid(String accessToken,String unionid){
    	String userId = "";
    	DingTalkClient client = new DefaultDingTalkClient(GeniusConfig.OAPI_HOST+"/user/getUseridByUnionid");
    	OapiUserGetUseridByUnionidRequest request = new OapiUserGetUseridByUnionidRequest();
    	request.setUnionid(unionid);
    	request.setHttpMethod("GET");
    	OapiUserGetUseridByUnionidResponse response = null;
    	try {
			response = client.execute(request, accessToken);
			if(response.getErrcode() == 0){
				userId = response.getUserid();
			}
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return userId;
    }
  //获取成员
    public static OapiUserGetResponse getUserInfo(String accessToken, String userid){

    	DingTalkClient client = new DefaultDingTalkClient(GeniusConfig.OAPI_HOST+"/user/get");
    	OapiUserGetRequest request = new OapiUserGetRequest();
    	request.setUserid(userid);
    	request.setHttpMethod("GET");
    	OapiUserGetResponse response = null;
		try {
			response = client.execute(request, accessToken);
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return response;
    }
    /**
     * 
     * @param accessToken
     * @param departmentId
     * @param offset
     * @param size
     * @param order
     * @return
     * @throws Exception
     * entry_asc：代表按照进入部门的时间升序，

		entry_desc：代表按照进入部门的时间降序，
		
		modify_asc：代表按照部门信息修改时间升序，
		
		modify_desc：代表按照部门信息修改时间降序，
		
		custom：代表用户定义(未定义时按照拼音)排序
     */
    //获取部门成员
    public static OapiUserSimplelistResponse getDepartmentUserNew(
            String accessToken,
            long departmentId,
            Long offset,
            Long size,
            String order)
            throws Exception {

    	DingTalkClient client = new DefaultDingTalkClient(GeniusConfig.OAPI_HOST+"/user/simplelist");
    	OapiUserSimplelistRequest request = new OapiUserSimplelistRequest();
    	request.setDepartmentId(departmentId);
    	request.setOffset(offset);
    	request.setSize(size);
    	request.setOrder(order);
    	request.setHttpMethod("GET");

    	OapiUserSimplelistResponse response = client.execute(request, accessToken);
    	 return response;
    }
    /**
     * 
     * @param accessToken
     * @param departmentId
     * @param offset
     * @param size
     * @param order
     * @return
     * @throws Exception
     * entry_asc：代表按照进入部门的时间升序，

		entry_desc：代表按照进入部门的时间降序，
		
		modify_asc：代表按照部门信息修改时间升序，
		
		modify_desc：代表按照部门信息修改时间降序，
		
		custom：代表用户定义(未定义时按照拼音)排序
     */
    //获取部门成员
    public static List<Userlist> getDepartmentUserSimple(
            String accessToken,
            long departmentId,
            Long offset,
            Long size,
            String order){

    	DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/simplelist");
    	OapiUserSimplelistRequest request = new OapiUserSimplelistRequest();
    	request.setDepartmentId(departmentId);
    	if(offset != null){
    		request.setOffset(offset);
    	}
    	if(size != null){
    		request.setSize(size);
    	}
    	if(order != null){
    		request.setOrder(order);
    	}
    	request.setHttpMethod("GET");
    	List<Userlist> list = null;
    	OapiUserSimplelistResponse response;
		try {
			response = client.execute(request, accessToken);
			list = response.getUserlist();
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(list == null){
			list = new ArrayList<Userlist>();
		}
    	 return list;
    }
    /**
     * 签名计算
     * @timestamp 时间戳  @accessKey appid @appSecret
     * @return
     */
    public static String sign(Long timestamp,String accessKey,String appSecret){
    	if(timestamp == null){
    		timestamp = System.currentTimeMillis();
    	}
    	String stringToSign = timestamp.toString();
    	Mac mac = null;
    	byte[] signatureBytes = null;
		try {
			mac = Mac.getInstance("HmacSHA256");
			mac.init(new SecretKeySpec(appSecret.getBytes("UTF-8"), "HmacSHA256"));
			signatureBytes = mac.doFinal(stringToSign.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	String signature = new String(Base64.encodeBase64(signatureBytes));
    	String urlEncodeSignature = urlEncode(signature,"utf-8");
		return urlEncodeSignature;
    }
 // encoding参数使用utf-8
    public static String urlEncode(String value, String encoding) {
        if (value == null) {
            return "";
        }
        try {
            String encoded = URLEncoder.encode(value, encoding);
            return encoded.replace("+", "%20").replace("*", "%2A")
                .replace("~", "%7E").replace("/", "%2F");
        } catch (UnsupportedEncodingException e) {
            throw new IllegalArgumentException("FailedToEncodeUri", e);
        }
    }
    
}
